﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EC.Admin.Controllers
{
    using EC.Application.Interface;
    using EC.Entity;
    using EC.Entity.Query;
    using EC.Entity.Request.DepositRecord;
    
    /// <summary>
    /// 存款控制器
    /// </summary>
    public class DepositRecordController : BaseController
    {
        #region 注入
        /// <summary>
        /// 存款记录数据接口
        /// </summary>
        private readonly DepositRecordService _depositRecordService;

        /// <summary>
        /// 用户组数据接口
        /// </summary>
        private readonly UserGroupService _userGroupService;

        /// <summary>
        /// 商户数据接口
        /// </summary>
        private readonly MerchantService _merchantService;
        
        /// <summary>
        /// 
        /// </summary>
        public DepositRecordController(UserGroupService userGroupService, DepositRecordService depositRecordService, MerchantService merchantService, LoginService loginService) : base(loginService)
        {
            _depositRecordService = depositRecordService;
            _userGroupService = userGroupService;
            _merchantService = merchantService;
        }
        #endregion

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns>视图</returns>
        public IActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<?></returns>
        public IActionResult DepositRecordQuery(DepositRecordQuery query)
        {
            query.MerchantIds = new List<int>() { -1 };

            //获取公司
            var merchant = _merchantService.Get(MerchantId);
            //验证
            if(merchant != null && !string.IsNullOrEmpty(merchant.ProxyId))
            {
                var ids = merchant.ProxyId.Split(',');
                foreach(var item in ids)
                {
                    query.MerchantIds.Add(Convert.ToInt32(item));
                }
            }

            var list = _depositRecordService.GetPager(query);

            return PartialView("_DepositRecord", list);
        }


        /// <summary>
        /// 首页
        /// </summary>
        /// <returns>视图</returns>
        public IActionResult MatchRecord(int id)
        {
            return View();
        }

        // <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<?></returns>
        public IActionResult MatchRecordQuery(MatchRecordQuery query)
        {
            query.MerchantIds = new List<int>() { MerchantId };

            //获取公司
            var merchant = _merchantService.Get(MerchantId);
            //验证
            if (merchant != null && !string.IsNullOrEmpty(merchant.ProxyId))
            {
                var ids = merchant.ProxyId.Split(',');
                foreach (var item in ids)
                {
                    query.MerchantIds.Add(Convert.ToInt32(item));
                }
            }

            var list = _depositRecordService.MatchRecord(query);

            return PartialView("_MatchRecord", list);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public IActionResult AddOrEdit(int? id)
        {
            var model = _depositRecordService.Get(id);

            return View("Edit", model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private bool IsDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult SaveDepositRecord(SaveDepositRecordRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {

                # region 验证
                //商户
                if(!request.MerchantId.HasValue)
                {
                    throw new Exception("商户不能为空.");
                }
                //收款卡号
                if (string.IsNullOrEmpty(request.DepositCardNumber))
                {
                    throw new Exception("收款卡号不能为空.");
                }
                //交易类型

                //存款金额
                if (string.IsNullOrEmpty(request.DepositAmount))
                {
                    throw new Exception("存款金额最大保留两位小数，整数最多保留四位");
                }
                var depositAmountReg = new Regex(@"^(([1-9]\d{0,3})|0)(?:\.[0-9]{1,2})?$");
                if (!depositAmountReg.IsMatch(request.DepositAmount))
                {
                    throw new Exception("存款金额最大保留两位小数，整数最多保留四位");
                }
                //名称
                //if (string.IsNullOrEmpty(request.Name))
                //{
                //    throw new Exception("标签名称不能为空.");
                //}

                //var nameReg = new Regex(@"^.{2,40}$");
                //if (!nameReg.IsMatch(request.Name))
                //{
                //    throw new Exception("标签名称必须介于 2 和 40 之间");
                //}
                //存款时间
                if (!string.IsNullOrEmpty(request.DepositDate))
                {
                    if (!IsDate(request.DepositDate))
                    {
                        throw new Exception("存款时间格式有误.");
                    }
                }
                //客户银行名称
                if (!string.IsNullOrEmpty(request.ClientBankName))
                {
                    var clientBankNameReg = new Regex(@"^.{2,20}$");
                    if (!clientBankNameReg.IsMatch(request.ClientBankName))
                    {
                        throw new Exception("客户银行名称必须介于 2 和 20 之间");
                    }
                }
                //客户银行姓名
                if (!string.IsNullOrEmpty(request.ClientCardName))
                {
                    var clientCardNameReg = new Regex(@"^.{2,20}$");
                    if (!clientCardNameReg.IsMatch(request.ClientCardName))
                    {
                        throw new Exception("客户银行姓名称必须介于 2 和 20 之间");
                    }
                }
                //客户银行卡号
                if (!string.IsNullOrEmpty(request.ClientCardNumber))
                {
                    var clientCardNumberReg = new Regex(@"^.{2,20}$");
                    if (!clientCardNumberReg.IsMatch(request.ClientCardNumber))
                    {
                        throw new Exception("客户银行卡号必须介于 2 和 20 之间");
                    }
                }
                #endregion

                request.ClientOrderNo = $"ts_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}";
                request.CreatedBy = UserId;

                response = _depositRecordService.SaveDepositRecord(request);
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return Json(response);
        }
    }
}
